package org.byqh.dqeai.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import org.byqh.dqeai.common.Json;
import org.byqh.dqeai.dto.SysSetupDTO;
import org.byqh.dqeai.dto.common.InsertOrUpdateDto;
import org.byqh.dqeai.entity.SysSetup;
import org.byqh.dqeai.entity.SysSetupApp;
import org.byqh.dqeai.entity.SysSetupRuntime;
import org.byqh.dqeai.entity.proxy.SysSetupProxy;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sysSetup")
@Tag(name = "系统[SysSetup] - 设置管理")
public class SysSetupController extends BaseController<SysSetup, SysSetupProxy> {

    /**
     * 查询列表
     */
    @PostMapping(value = "/selectList")
    public Json<List<SysSetupDTO>> selectList(@RequestBody SysSetupDTO dto) {

        List<SysSetupDTO> result = this.listImpl(SysSetupDTO.class, null).getData();

        for (SysSetupDTO newItem : result) {
            // 查询关联app
            {
                List<SysSetupApp> listApp = easyEntityQuery.queryable(SysSetupApp.class)
                        .where(s -> s.setupId().eq(newItem.getSetupId()))
                        .toList();

                newItem.setAppList(listApp);
            }

            // 查询关联runtime
            {
                List<SysSetupRuntime> listRuntime = easyEntityQuery.queryable(SysSetupRuntime.class)
                        .where(s -> s.setupId().eq(newItem.getSetupId()))
                        .toList();

                newItem.setRuntimeList(listRuntime);
            }
        }

        return Json.success(result);
    }

    /**
     * 插入或更新
     */
    @PostMapping(value = "/insertOrUpdate")
    public Json<Boolean> insertOrUpdate(@RequestBody InsertOrUpdateDto<SysSetupDTO> dto) {
        for (SysSetupDTO item : dto.getList()) {
            this.delete(item.getSetupId());

            SysSetup newItem = new SysSetup();
            BeanUtils.copyProperties(item, newItem);

            this.save(newItem);

            easyEntityQuery.insertable(item.getAppList()).executeRows();
            easyEntityQuery.insertable(item.getRuntimeList()).executeRows();
        }

        return Json.success();
    }

    @PostMapping(value = "/delete")
    public Json<Boolean> delete(@RequestParam String id) {

        return this.remove(id);
    }
}